<script setup lang="ts">
import { onMounted, ref, reactive, onUnmounted, onActivated, watch } from 'vue';
import { Global } from "../../Global";
import { HttpHelper } from "../../lib/HttpHelper";
import { ElTable, ElForm } from 'element-plus';
import DocEditor from '../../components/DocEditor.vue';

const isLoading = ref(false);
const isBusy = ref(false);
const listDatas = ref(<any[]>[]);
const pageNumber = ref(1);
const servicePath = '/PlanCheckInItem';
const total = ref(0);
const formData = ref(<any>{});
var editingData: any;
const dialogFormVisible = ref(false);
const multipleTableRef = ref<InstanceType<typeof ElTable>>();
const multipleSelection = ref<any[]>([]);
const formRef = ref<InstanceType<typeof ElForm>>();

const searchData = reactive({

    Title: null,
    SubTitle: null,

    PageIndex: 0,
    PageSize: 10
});

const rules = reactive({
    Title: [{ required: true, message: '请输入标题', trigger: 'blur' }],
    SubTitle: [{ required: true, message: '请输入副标题', trigger: 'blur' }],
    Intro: [{ required: true, message: '请输入介绍', trigger: 'blur' }],
});

const resetFormData = () => {
    formData.value = {
        Title: null,
        SubTitle: null,
        Intro: null,
        Mode: 1,
        OpenMode: 2,
        OwnerId: 0,

    };
}

onActivated(() => {
    bindList();
});

onUnmounted(() => {
    console.log("卸载了");
});

const refreshClick = () => {
    bindList();
}

const bindList = async () => {
    isLoading.value = true;
    try {
        searchData.PageIndex = pageNumber.value - 1;
        var list = JSON.parse(await HttpHelper.postJson(`${servicePath}/List`, searchData));

        total.value = list.Total;
        listDatas.value.splice(0, listDatas.value.length);
        listDatas.value.push(...list.Datas);

        if (listDatas.value.length == 0 && pageNumber.value > 1) {
            pageNumber.value--;
            bindList();
        }
    } catch (error) {
        Global.showError(error);
    }
    finally {
        isLoading.value = false;
    }
}

const addClick = () => {
    resetFormData();
    dialogFormVisible.value = true;
}

const editClick = (row: any) => {
    resetFormData();
    for (var p in row) {
            formData.value[p] = row[p];
        
    }
    editingData = row;
    dialogFormVisible.value = true;
}

const deleteClick = async () => {
    if (isLoading.value)
        return;

    if (multipleSelection.value.length == 0) {
        Global.showInfo("请选择需要删除的数据");
        return;
    }

    if (confirm("确定删除吗？")) {
        try {
            isLoading.value = true;
            var requestData = new FormData();
            multipleSelection.value.forEach(x => {
                requestData.append("ids", x.id);

            });
            await HttpHelper.postFormData(`${servicePath}/Delete`, requestData);
            multipleSelection.value.forEach(x => {
                var index = listDatas.value.findIndex(m => m == x);
                if (index >= 0) {
                    listDatas.value.splice(index, 1);
                }

            });
            multipleTableRef.value?.clearSelection();
        } catch (error) {
            Global.showError(error);
        }
        finally {
            isLoading.value = false;
        }
    }
}

const handleSelectionChange = (selecteds: any[]) => {
    multipleSelection.value = selecteds;
}

const submitClick = async () => {
    try {
        await formRef.value?.validate();
    } catch (error) {
        return;
    }

    try {
        isBusy.value = true;
        if (formData.value.id) {
            var obj = JSON.parse(await HttpHelper.postJson(`${servicePath}/Modify`, formData.value));
            listDatas.value.splice(listDatas.value.indexOf(editingData), 1, obj);
        }
        else {
            formData.value = JSON.parse(await HttpHelper.postJson(`${servicePath}/Add`, formData.value));
            listDatas.value.splice(0, 0, formData.value);
        }
        dialogFormVisible.value = false;
    } catch (error) {
        Global.showError(error);
    }
    finally {
        isBusy.value = false;

    }
}

const goSearch = () => {
    pageNumber.value = 1;
    bindList();
}
</script>
<template>
    <div class="page-view-main">
        <div
            style="padding: var(--page-padding); flex: 1 1 0%; min-height: 0px; display: flex; flex-direction: column;">
            <div class="page-view-panel">
                <div style="display: flex; flex-direction: row; margin-bottom: 10px;">
                    <div style="flex: 1 1 0%;">
                      
                        <el-input v-model="searchData.Title" placeholder="标题" @keypress.native.enter.prevent="goSearch"
                            style="margin-left: 5px;width: 150px;" />
                        <el-input v-model="searchData.SubTitle" placeholder="副标题"
                            @keypress.native.enter.prevent="goSearch" style="margin-left: 5px;width: 150px;" />
                     

                        <el-button icon="Search" @click="goSearch" style="margin-left: 5px;"></el-button>
                    </div>
                    <div><el-button-group class="ml-4">
                            <el-button type="default" icon="Plus" @click="addClick">添加</el-button>
                            <el-button type="default" icon="Refresh" @click="refreshClick">刷新</el-button>
                            <el-button type="default" icon="Delete" @click="deleteClick">删除</el-button>
                        </el-button-group></div>
                </div>

                <el-table ref="multipleTableRef" @selection-change="handleSelectionChange" :data="listDatas"
                    cell-class-name="tb-cell" header-cell-class-name="tb-header-cell" table-layout="auto"
                    v-loading="isLoading" style="flex:1;min-height:0px;">
                    <el-table-column type="selection" width="42" fixed="left" />
                    <el-table-column prop="id" label="id" />
                    <el-table-column prop="Title" label="标题" />
                    <el-table-column prop="SubTitle" label="副标题" />
                    <el-table-column label="打卡方式">
                        <template #default="scope">
                            <el-tag v-if="scope.row.Mode == 1" type="info" effect="light">时间段</el-tag>
                            <el-tag v-if="scope.row.Mode == 2" type="info" effect="light">时间点</el-tag>
                        </template>
                    </el-table-column>

               
                    <el-table-column prop="CreateTime" label="创建时间" :formatter="Global.formatUTCToLocal" />
                    <el-table-column prop="JoinCount" label="加入人数" />
                    <el-table-column label="操作" fixed="right">
                        <template #default="scope">
                            <el-button size="small" type="primary" @click="editClick(scope.row)">
                                编辑
                            </el-button>
                        </template>
                    </el-table-column>
                </el-table>
                <div>
                    <el-pagination @current-change="bindList" small background layout="prev, pager, next" :total="total"
                        v-model:current-page="pageNumber" class="mt-4" style="margin-top: 10px;" />
                </div>
            </div>
        </div>

        <el-dialog v-model="dialogFormVisible" :title="formData.id ? '编辑' : '新增'" :close-on-click-modal="false"
            style="width:70%">
            <el-form ref="formRef" :model="formData" label-width="auto" :rules="rules">

                <el-form-item label="标题" prop="Title">
                    <el-input v-model="formData.Title" />
                </el-form-item>
                <el-form-item label="副标题" prop="SubTitle">
                    <el-input v-model="formData.SubTitle" />
                </el-form-item>
                <el-form-item label="介绍" prop="Intro">
                    <doc-editor v-model="formData.Intro"></doc-editor>
                </el-form-item>
                <el-form-item label="打卡方式" prop="Mode">
                    <el-select v-model="formData.Mode" placeholder="Select">

                        <el-option :key="1" label="时间段" :value="1" />
                        <el-option :key="2" label="时间点" :value="2" />
                    </el-select>
                </el-form-item>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="dialogFormVisible = false">取消</el-button>
                    <el-button type="primary" :loading="isBusy" @click="submitClick">
                        确 定
                    </el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>
<style scoped lang="scss"></style>